using System;
using System.Collections.Generic;

namespace Lichtspiel.ECSystem.Behaviors
{
    /// <summary>
    /// A Holder for several Behaviors. Child-classes have to call BehaviorFinished() when all behaviors are finished.
    /// </summary>
    public abstract class BehaviorHolder : Behavior
    {
        protected List<Behavior> behaviors = new List<Behavior>();

        protected BehaviorHolder()
            : base() { }

        protected BehaviorHolder(Action finished)
            : base(finished) {}

        protected override void Initialize() {}

        public override void Update(GameTime time) {
            base.Update(time);

            if (behaviors.Count <= 0) {
                BehaviorFinished(); // tell owner that composite is finished
            }
        }

        internal virtual void BehaviorFinished(Behavior behavior) {
            behavior.Stop();
            behaviors.Remove(behavior);
        }

        /// <summary>
        /// Adds a Behavior to the Holder. Only add behaviors before holder has been started.
        /// </summary>
        /// <param name="behavior"></param>
        public void AddBehavior(Behavior behavior) {
            behaviors.Add(behavior);
        }

        internal override void Stop() {
            base.Stop();

            foreach (Behavior b in behaviors) {
                b.Stop();
            }

            behaviors.Clear();
        }
    }
}